<template>
  <div class="logs-management">
    <!-- 查询表单 -->
    <v-card class="mb-4" elevation="10" rounded="lg">
      <v-card-title>
        <v-icon left>mdi-cog-outline</v-icon>
        操作日志管理
      </v-card-title>
      <v-card-text>
        <v-form @submit.prevent="handleQuery">
          <v-row>
            <v-col cols="12" md="2">
              <v-select
                v-model="queryForm.logType_EQ"
                :items="logTypeOptions"
                label="日志类型"
                clearable
                variant="outlined"
                density="compact"
              />
            </v-col>
            <v-col cols="12" md="2">
              <v-select
                v-model="queryForm.level_EQ"
                :items="logLevelOptions"
                label="日志等级"
                clearable
                variant="outlined"
                density="compact"
              />
            </v-col>
            <v-col cols="12" md="2">
              <v-select
                v-model="queryForm.operationType_EQ"
                :items="operationTypeOptions"
                label="操作类型"
                clearable
                variant="outlined"
                density="compact"
              />
            </v-col>
            <v-col cols="12" md="2">
              <v-select
                v-model="queryForm.moduleId_EQ"
                :items="moduleTypeOptions"
                label="操作模块"
                clearable
                variant="outlined"
                density="compact"
              />
            </v-col>
            <v-col cols="12" md="2">
              <v-text-field
                v-model="queryForm.username_EQ"
                label="操作人账号"
                clearable
                variant="outlined"
                density="compact"
              />
            </v-col>
            <v-col cols="12" md="2">
              <v-row>
                <v-col cols="6">
                  <v-text-field
                    v-model="dateRange.start"
                    label="开始时间"
                    type="datetime-local"
                    variant="outlined"
                    density="compact"
                  />
                </v-col>
                <v-col cols="6">
                  <v-text-field
                    v-model="dateRange.end"
                    label="结束时间"
                    type="datetime-local"
                    variant="outlined"
                    density="compact"
                  />
                </v-col>
              </v-row>
            </v-col>
          </v-row>
          <v-row class="mt-2">
            <v-col cols="12" class="d-flex align-center">
              <v-btn
                type="submit"
                color="primary"
                :loading="loading"
                prepend-icon="mdi-magnify"
                class="mr-2"
              >
                查询
              </v-btn>
              <v-btn
                color="secondary"
                variant="outlined"
                @click="handleReset"
                prepend-icon="mdi-refresh"
                class="mr-2"
              >
                重置
              </v-btn>
              <v-menu>
                <template #activator="{ props }">
                  <v-btn
                    color="success"
                    variant="outlined"
                    v-bind="props"
                    prepend-icon="mdi-download"
                    :disabled="list.length === 0"
                  >
                    导出
                  </v-btn>
                </template>
                <v-list>
                  <v-list-item @click="handleExport('csv')">
                    <v-list-item-title>
                      <v-icon left>mdi-file-delimited</v-icon>
                      导出CSV
                    </v-list-item-title>
                  </v-list-item>
                  <v-list-item @click="handleExport('excel')">
                    <v-list-item-title>
                      <v-icon left>mdi-file-excel</v-icon>
                      导出Excel
                    </v-list-item-title>
                  </v-list-item>
                  <v-list-item @click="handleExport('json')">
                    <v-list-item-title>
                      <v-icon left>mdi-code-json</v-icon>
                      导出JSON
                    </v-list-item-title>
                  </v-list-item>
                </v-list>
              </v-menu>
            </v-col>
          </v-row>
        </v-form>
      </v-card-text>
    </v-card>
    <!-- 数据表格 -->
    <v-card elevation="10" rounded="lg">
      <v-data-table
        v-model:page="queryForm.pageNo"
        v-model:items-per-page="queryForm.pageSize"
        :headers="headers"
        :items="list"
        :loading="loading"
        :items-length="total"
        :items-per-page-options="[10, 20, 50, 100]"
        loading-text="正在加载..."
        no-data-text="暂无数据"
        @update:page="handlePageChange"
        @update:items-per-page="handleSizeChange"
      >
        <!-- 序号列 -->
        <template #item.index="{ index }">
          {{ (queryForm.pageNo - 1) * queryForm.pageSize + index + 1 }}
        </template>
        <!-- 日志类型字典列 -->
        <template #item.logType="{ item }">
          <v-chip color="primary" size="small" variant="flat">
            {{ getLogTypeName(item.logType) }}
          </v-chip>
        </template>
        <!-- 日志等级字典列 -->
        <template #item.level="{ item }">
          <v-chip color="info" size="small" variant="flat">
            {{ getLogLevelName(item.level) }}
          </v-chip>
        </template>
        <!-- 操作类型字典列 -->
        <template #item.operationType="{ item }">
          <v-chip color="success" size="small" variant="flat">
            {{ getOperationTypeName(item.operationType) }}
          </v-chip>
        </template>
        <!-- 模块类型字典列 -->
        <template #item.moduleId="{ item }">
          <v-chip color="warning" size="small" variant="flat">
            {{ getModuleTypeName(item.moduleId) }}
          </v-chip>
        </template>
        <!-- 创建时间列 -->
        <template #item.createTime="{ item }">
          {{ formatDateTime(item.createTime) }}
        </template>
        <!-- 日志描述列 -->
        <template #item.description="{ item }">
          <div class="text-truncate" style="max-width: 200px;">
            {{ item.description }}
          </div>
          <v-tooltip
            v-if="item.description && item.description.length > 50"
            activator="parent"
            location="top"
          >
            {{ item.description }}
          </v-tooltip>
        </template>
        <!-- 操作列 -->
        <template #item.actions="{ item }">
          <v-btn
            size="small"
            color="primary"
            variant="text"
            @click="viewDetail(item)"
            prepend-icon="mdi-eye"
          >
            详情
          </v-btn>
        </template>
      </v-data-table>
    </v-card>
    <!-- 详情弹窗 -->
    <OperationDetail
      v-model="detailDialog"
      :log-data="selectedLog"
      :log-type-dict="logTypeOptions"
      :log-level-dict="logLevelOptions"
      :operation-type-dict="operationTypeOptions"
      :module-type-dict="moduleTypeOptions"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { getList } from '@/api/system/logs/OperationLogManagementApi'
import { useMessage } from '@/composables/useMessage'
import { exportData, formatDateTimeForExport, type ExportFormat } from '@/utils/export'
import { useDict } from '@/composables/useDict'
import type { DictItem } from '@/utils/dict'
import OperationDetail from './components/OperationDetail.vue'

// 类型定义
interface LogItem {
  id: string
  logType: string
  level: string
  moduleId: string
  username: string
  realName: string
  operationType: string
  runTime: string
  createTime: string
  description: string
  method: string
  args: string
  returnValue: string
}

interface QueryForm {
  pageNo: number
  pageSize: number
  username_EQ: string
  realName_LIKE: string
  logType_EQ: string
  level_EQ: string
  operationType_EQ: string
  moduleId_EQ: string
  createTime_BEGIN: string
  createTime_END: string
}

interface TimeShortcut {
  text: string
  days: number
}

const { show: showMessage } = useMessage()
const loading = ref(false)
const list = ref<LogItem[]>([])
const total = ref(0)
const detailDialog = ref(false)
const selectedLog = ref<LogItem | null>(null)

// 查询表单
const queryForm = reactive<QueryForm>({
  pageNo: 1,
  pageSize: 10,
  username_EQ: '',
  realName_LIKE: '',
  logType_EQ: '',
  level_EQ: '',
  operationType_EQ: '',
  moduleId_EQ: '',
  createTime_BEGIN: '',
  createTime_END: ''
})

// 日期范围
const dateRange = reactive({
  start: '',
  end: ''
})

// 字典
const { getDictList } = useDict()
const logTypeOptions = ref<DictItem[]>([])
const logLevelOptions = ref<DictItem[]>([])
const operationTypeOptions = ref<DictItem[]>([])
const moduleTypeOptions = ref<DictItem[]>([])

const getLogTypeName = (val: string) => {
  const found = logTypeOptions.value.find(item => item.dictValue === val)
  return found ? found.dictName : val
}
const getLogLevelName = (val: string) => {
  const found = logLevelOptions.value.find(item => item.dictValue === val)
  return found ? found.dictName : val
}
const getOperationTypeName = (val: string) => {
  const found = operationTypeOptions.value.find(item => item.dictValue === val)
  return found ? found.dictName : val
}
const getModuleTypeName = (val: string) => {
  const found = moduleTypeOptions.value.find(item => item.dictValue === val)
  return found ? found.dictName : val
}

// 表格列配置
const headers = [
  { title: '序号', key: 'index', width: 80, sortable: false },
  { title: '日志类型', key: 'logType', width: 100, sortable: false },
  { title: '日志等级', key: 'level', width: 100, sortable: false },
  { title: '被操作的系统模块', key: 'moduleId', width: 140, sortable: false },
  { title: '操作人账号', key: 'username', width: 110, sortable: false },
  { title: '操作人名称', key: 'realName', width: 110, sortable: false },
  { title: '操作类型', key: 'operationType', width: 100, sortable: false },
  { title: '运行时间(ms)', key: 'runTime', width: 110, sortable: false },
  { title: '创建时间', key: 'createTime', width: 120, sortable: false },
  { title: '日志描述', key: 'description', width: 200, sortable: false },
  { title: '操作', key: 'actions', width: 110, sortable: false }
]

// 格式化日期时间
const formatDateTime = (dateTime: string): string => {
  if (!dateTime) return ''
  return new Date(dateTime).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 查询数据
const handleQuery = () => {
  if (dateRange.start) {
    queryForm.createTime_BEGIN = new Date(dateRange.start).toISOString().replace('T', ' ').slice(0, 19)
  } else {
    queryForm.createTime_BEGIN = ''
  }
  if (dateRange.end) {
    queryForm.createTime_END = new Date(dateRange.end).toISOString().replace('T', ' ').slice(0, 19)
  } else {
    queryForm.createTime_END = ''
  }
  queryForm.pageNo = 1
  fetchData()
}

// 重置查询
const handleReset = () => {
  queryForm.username_EQ = ''
  queryForm.realName_LIKE = ''
  queryForm.logType_EQ = ''
  queryForm.level_EQ = ''
  queryForm.operationType_EQ = ''
  queryForm.moduleId_EQ = ''
  queryForm.createTime_BEGIN = ''
  queryForm.createTime_END = ''
  dateRange.start = ''
  dateRange.end = ''
  queryForm.pageNo = 1
  fetchData()
}

// 页码变化
const handlePageChange = (page: number) => {
  queryForm.pageNo = page
  fetchData()
}

// 页大小变化
const handleSizeChange = (size: number) => {
  queryForm.pageSize = size
  queryForm.pageNo = 1
  fetchData()
}

// 获取数据
const fetchData = async () => {
  try {
    loading.value = true
    const { data } = await getList(queryForm)
    if (data) {
      list.value = data.rows || []
      total.value = data.total || 0
    }
  } catch (error) {
    console.error('获取操作日志数据失败:', error)
    showMessage('获取操作日志数据失败', 'error')
  } finally {
    loading.value = false
  }
}

// 查看详情
const viewDetail = (item: LogItem) => {
  selectedLog.value = item
  detailDialog.value = true
}

// 导出数据
const handleExport = (format: ExportFormat) => {
  try {
    if (list.value.length === 0) {
      showMessage('没有可导出的数据', 'warning')
      return
    }
    const exportList = list.value.map(item => ({
      ...item,
      logType: getLogTypeName(item.logType),
      level: getLogLevelName(item.level),
      operationType: getOperationTypeName(item.operationType),
      moduleId: getModuleTypeName(item.moduleId),
      createTime: formatDateTimeForExport(item.createTime)
    }))
    const timestamp = new Date().toISOString().slice(0, 19).replace(/[:-]/g, '')
    const filename = `操作日志_${timestamp}`
    exportData(exportList, {
      filename,
      format,
      fields: ['logType', 'level', 'moduleId', 'username', 'realName', 'operationType', 'runTime', 'createTime', 'description'],
      headers: ['日志类型', '日志等级', '被操作的系统模块', '操作人账号', '操作人名称', '操作类型', '运行时间(ms)', '创建时间', '日志描述']
    })
    showMessage(`${format.toUpperCase()}文件导出成功`, 'success')
  } catch (error) {
    console.error('导出失败:', error)
    showMessage('导出失败', 'error')
  }
}

onMounted(async () => {
  logTypeOptions.value = await getDictList('log_type')
  logLevelOptions.value = await getDictList('log_level')
  operationTypeOptions.value = await getDictList('log_operation_type')
  moduleTypeOptions.value = await getDictList('log_model_type')
  fetchData()
})
</script>

<style scoped>
.logs-management {
  padding: 16px;
}
.text-truncate {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>
